package com.looyee.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.looyee.wxpay.api.WxPayApi;
import com.looyee.wxpay.business.WxPayBusiness;
import com.looyee.wxpay.common.RandomStringGenerator;
import com.looyee.wxpay.common.Signature;
import com.looyee.wxpay.config.WxPayConfiguration;
import com.looyee.wxpay.entity.*;
import com.looyee.wxpay.notify.WxPayNotify;
import com.looyee.wxpay.notify.WxPayNotifyCallback;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lxw
 * @date 2018/5/17
 * @description
 */
@Slf4j
@RestController
@RequestMapping(value = "/api/pay")
public class TestPayController2 {

	@Autowired
	WxPayApi payApi;

	@Autowired
	WxPayBusiness payBusiness;

	@Autowired
	WxPayNotify payNotify;

	private String key = "test";
	private String appid = "test";
	private String mchid = "test";
	private String outTradeNo = "test";
	private String certPassword = "test";
	private String notify = "test";
	private String certFilePath = "test";


	@RequestMapping(value = "testwxalpay")
	public String test(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String userAgent = request.getHeader("User-Agent");
		String agent = userAgent.toLowerCase();
		if (agent.indexOf("micromessenger") > 0) {
			System.out.println("微信...");

			WxUnifiedOrderReq orderReq = new WxUnifiedOrderReq();

			orderReq.setKey(key);
			orderReq.setRequestUrl(WxPayConfiguration.UNIFIEDORDER);

			orderReq.setAppid(appid);
			orderReq.setMch_id(mchid);
			orderReq.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
			orderReq.setSign_type("MD5");
			orderReq.setBody("28快运测试");
//			orderReq.setAttach("通过此字段来做具体的实际业务处理");
			orderReq.setOut_trade_no("AFTC201907080930344084997");
			orderReq.setTotal_fee(1);
			orderReq.setSpbill_create_ip("113.119.132.41");
			orderReq.setNotify_url(notify);
			orderReq.setTrade_type("MWEB");

			JSONObject jsonObject = new JSONObject();
			JSONObject params = new JSONObject();
			params.put("type", "Wap");
			params.put("wap_url", "http://anfa.pcluo.com");
			params.put("wap_name", "28快运下单");
			jsonObject.put("h5_info", params);
			orderReq.setScene_info(jsonObject.toJSONString());

			String sign = Signature.getSign(orderReq.toMap());
			orderReq.setSign(sign);

			WxUnifiedOrderRes unifiedorder = payApi.unifiedorder(orderReq);

			return unifiedorder.getMweb_url();
			//MWEB

		} else if (agent.indexOf("alipayclient") > 0) {
			System.out.println("支付宝...");
		}
		return null;
	}

	@RequestMapping(value = "/testnative")
	public void testnative(HttpServletResponse response) {

		try {
			WxUnifiedOrderReq orderReq = new WxUnifiedOrderReq();

			orderReq.setKey(key);
			orderReq.setRequestUrl(WxPayConfiguration.UNIFIEDORDER);

			orderReq.setAppid(appid);
			orderReq.setMch_id(mchid);
			orderReq.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
			orderReq.setSign_type("MD5");
			orderReq.setBody("28快运测试");
//			orderReq.setAttach("通过此字段来做具体的实际业务处理");
			orderReq.setOut_trade_no("AFTC201907080920164084997");
			orderReq.setTotal_fee(1);
			orderReq.setSpbill_create_ip("113.119.132.41");
			orderReq.setNotify_url(notify);
			orderReq.setTrade_type("NATIVE");
			String sign = Signature.getSign(orderReq.toMap());
			orderReq.setSign(sign);

			WxUnifiedOrderRes unifiedorder = payApi.unifiedorder(orderReq);
			log.info("unifiedOrderRes = {}", unifiedorder);

			String code_url = unifiedorder.getCode_url();

			Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
			// 指定编码格式
			hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
			// 指定纠错级别(L--7%,M--15%,Q--25%,H--30%)
			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
			// 编码内容,编码类型(这里指定为二维码),生成图片宽度,生成图片高度,设置参数
			code_url = "http://192.168.1.184:8080/api/pay/testwxalpay";
			BitMatrix bitMatrix = new MultiFormatWriter().encode(code_url, BarcodeFormat.QR_CODE, 200, 200, hints);

			response.setHeader("Cache-Control", "no-store");
			response.setHeader("Pragma", "no-cache");
			response.setDateHeader("Expires", 0);
			response.setContentType("image/png");

			response.setHeader("Content-Disposition", "attachment;filename=" + "20190708.png");
			OutputStream outputStream = response.getOutputStream();
			MatrixToImageWriter.writeToStream(bitMatrix, "png", outputStream);
			outputStream.flush();
			outputStream.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@RequestMapping(value = "/testwxpay")
	public String testwxpay() {

		try {
			WxUnifiedOrderReq orderReq = new WxUnifiedOrderReq();

			orderReq.setKey(key);
			orderReq.setRequestUrl(WxPayConfiguration.UNIFIEDORDER);

			orderReq.setAppid(appid);
			orderReq.setMch_id(mchid);
			orderReq.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
			orderReq.setSign_type("MD5");
			orderReq.setBody("28快运测试");
//			orderReq.setAttach("通过此字段来做具体的实际业务处理");
			orderReq.setOut_trade_no("AFTC201907080920164084997");
			orderReq.setTotal_fee(1);
			orderReq.setSpbill_create_ip("113.119.132.41");
			orderReq.setNotify_url(notify);
			orderReq.setTrade_type("NATIVE");
			String sign = Signature.getSign(orderReq.toMap());
			orderReq.setSign(sign);

			WxUnifiedOrderRes unifiedorder = payApi.unifiedorder(orderReq);
			log.info("unifiedOrderRes = {}", unifiedorder);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return "sssss";
	}

	@RequestMapping(value = "/testmicropay")
	public String testmicropay() {

		try {
			WxMicroPayReq microPayReq = new WxMicroPayReq();

			microPayReq.setKey(key);

			microPayReq.setAppid(appid);
			microPayReq.setMch_id(mchid);
			microPayReq.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
			microPayReq.setSign_type("MD5");
			microPayReq.setBody("测试");
			microPayReq.setAttach("通过此字段来做具体的实际业务处理");
			microPayReq.setOut_trade_no(outTradeNo);
			microPayReq.setTotal_fee(1);
			microPayReq.setSpbill_create_ip("test");
			microPayReq.setAuth_code("test");
			String sign = Signature.getSign(microPayReq.toMap());
			microPayReq.setSign(sign);

			WxMicroPayRes microPayRes = payApi.micropay(microPayReq);
			log.info("microPayRes = {}", microPayRes);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return "sssss";
	}

	@RequestMapping(value = "/testreverse")
	public String testreverse() {

		try {
			WxReverseReq reverseReq = new WxReverseReq();

			reverseReq.setKey(key);

			reverseReq.setAppid(appid);
			reverseReq.setMch_id(mchid);
			reverseReq.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
			reverseReq.setSign_type("MD5");
			reverseReq.setOut_trade_no(outTradeNo);
			String sign = Signature.getSign(reverseReq.toMap());
			reverseReq.setSign(sign);

			WxReverseRes reverseRes = payApi.reverse(reverseReq, new File(certFilePath), certPassword);
			log.info("reverseRes = {}", reverseRes);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return "sssss";
	}

	@RequestMapping(value = "/notify", method = RequestMethod.POST)
	public String notify(HttpServletRequest request) {

		WxPayNotifyCallback call = new WxPayNotifyCallback() {
			@Override
			public Boolean doInNotifyBusiness(WxPayNotifyRes resData) {
				//这个是我在微信请求时传递的参数，可以根据不同的值用来做不同的业务处理
				String attach = resData.getAttach();
				if ("".equals(attach)) {
					//TODO doBusiness
				}
				String info = "<--------------------------我在这里做完了业务------------------------->";
				log.info(info);
				log.info("我拿到的数据要来做回调请求处理了");
				log.info("数据为 data = {}", resData);
				return true;
			}
		};

		String returnWx = payApi.notify(request, key, call);
		return returnWx;
	}

	@RequestMapping(value = "/testquery")
	public String testquery() {

		try {
			WxOrderQueryReq orderQueryReq = new WxOrderQueryReq();

			orderQueryReq.setKey(key);

			orderQueryReq.setAppid(appid);
			orderQueryReq.setMch_id(mchid);
			orderQueryReq.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
			orderQueryReq.setOut_trade_no("AFTC201907020643498028919-DAWZSA");
			String sign = Signature.getSign(orderQueryReq.toMap());
			orderQueryReq.setSign(sign);

			WxOrderQueryRes orderquery = payApi.orderquery(orderQueryReq);
			log.info("orderQueryRes = {}", orderquery);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return "sssss";
	}


	@RequestMapping(value = "/testcloseorder")
	public String testcloseorder() {

		try {
			WxCloseOrderReq closeOrderReq = new WxCloseOrderReq();

			closeOrderReq.setKey(key);

			closeOrderReq.setAppid(appid);
			closeOrderReq.setMch_id(mchid);
			closeOrderReq.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
			closeOrderReq.setOut_trade_no(outTradeNo);
			String sign = Signature.getSign(closeOrderReq.toMap());
			closeOrderReq.setSign(sign);

			WxCloseOrderRes closeOrderRes = payApi.closeorder(closeOrderReq);
			log.info("closeOrderRes = {}", closeOrderRes);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return "sssss";
	}


	@RequestMapping(value = "/testrefundorder")
	public String testrefundorder() {

		try {
			WxRefundOrderReq refudnOrderReq = new WxRefundOrderReq();

			refudnOrderReq.setKey(key);

			refudnOrderReq.setAppid(appid);
			refudnOrderReq.setMch_id(mchid);
			refudnOrderReq.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
			refudnOrderReq.setOut_trade_no("AFTC201907261530420240569-SAWCYD");
			refudnOrderReq.setOut_refund_no("AFUS201907261530543105378");
			refudnOrderReq.setTotal_fee(8900);
			refudnOrderReq.setRefund_fee(8900);
//			refudnOrderReq.setNotify_url(notify);
			String sign = Signature.getSign(refudnOrderReq.toMap());
			refudnOrderReq.setSign(sign);

			WxRefundOrderRes refudnOrderRes = payApi.refundorder(refudnOrderReq, new File(certFilePath), certPassword);

			log.info("refudnOrderRes = {}", refudnOrderRes);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return "sssss";
	}

	@RequestMapping(value = "/testrefundquery")
	public String testrefundquery() {

		try {
			WxRefundQueryReq refundQueryReq = new WxRefundQueryReq();

			refundQueryReq.setKey(key);

			refundQueryReq.setAppid(appid);
			refundQueryReq.setMch_id(mchid);
			refundQueryReq.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
			refundQueryReq.setOut_trade_no(outTradeNo);
//			refundQueryReq.setOut_refund_no("AFUS201907261530543105378");
			String sign = Signature.getSign(refundQueryReq.toMap());
			refundQueryReq.setSign(sign);

			WxRefundQueryRes refundQueryRes = payApi.refundquery(refundQueryReq);
			log.info("refundQueryRes = {}", refundQueryRes);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return "sssss";
	}


	@RequestMapping(value = "/testdownloadbill")
	public String testdownloadbill() {

		try {
			WxDownloadBillReq downloadBillReq = new WxDownloadBillReq();

			downloadBillReq.setKey(key);

			downloadBillReq.setAppid(appid);
			downloadBillReq.setMch_id(mchid);
			downloadBillReq.setBill_date("20190602");
			downloadBillReq.setBill_type("ALL");
			downloadBillReq.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
			String sign = Signature.getSign(downloadBillReq.toMap());
			downloadBillReq.setSign(sign);

			WxDownloadBillRes downloadBillRes = payApi.downloadbill(downloadBillReq);
			log.info("downloadBillRes = {}", downloadBillRes);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "sssss";
	}


	@RequestMapping(value = "/testauthcodetoopenid")
	public String testauthcodetoopenid() {

		try {
			WxAuthCodeToOpenIdReq authCodeToOpenIdReq = new WxAuthCodeToOpenIdReq();

			authCodeToOpenIdReq.setKey(key);

			authCodeToOpenIdReq.setAppid(appid);
			authCodeToOpenIdReq.setMch_id(mchid);
			authCodeToOpenIdReq.setAuth_code("135053961075989073");
			authCodeToOpenIdReq.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
			String sign = Signature.getSign(authCodeToOpenIdReq.toMap());
			authCodeToOpenIdReq.setSign(sign);

			WxAuthCodeToOpenIdRes authCodeToOpenIdRes = payApi.authcodetoopenid(authCodeToOpenIdReq);
			log.info("authCodeToOpenIdRes = {}", authCodeToOpenIdRes);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "sssss";
	}

	@RequestMapping(value = "/testdownloadfundflow")
	public String testdownloadfundflow() {

		try {
			WxDownloadFundFlowReq downloadFundFlowReq = new WxDownloadFundFlowReq();

			downloadFundFlowReq.setKey(key);

			downloadFundFlowReq.setAppid(appid);
			downloadFundFlowReq.setMch_id(mchid);

			downloadFundFlowReq.setSign_type("HMAC-SHA256");
			downloadFundFlowReq.setBill_date("20190606");
			downloadFundFlowReq.setAccount_type("Basic");

			downloadFundFlowReq.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
			String sign = Signature.getSign(downloadFundFlowReq.toMap());
			downloadFundFlowReq.setSign(sign);

			WxDownloadFundFlowRes downloadFundFlowRes = payApi.downloadfundflow(downloadFundFlowReq, new File(certFilePath), certPassword);

			log.info("downloadFundFlowRes = {}", downloadFundFlowRes);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "sssss";
	}

	@RequestMapping(value = "/testreport")
	public String testreport() {

		try {
			WxReportReq reportReq = new WxReportReq();

			reportReq.setKey(key);

			reportReq.setAppid(appid);
			reportReq.setMch_id(mchid);
			reportReq.setInterface_url("https://api.mch.weixin.qq.com/pay/unifiedorder");
			reportReq.setSign_type("MD5");
			reportReq.setExecute_time_(10000);
			reportReq.setReturn_code("SUCCESS");
			reportReq.setReturn_msg("OK");
			reportReq.setResult_code("SUCCESS");
			reportReq.setUser_ip("116.23.155.60");

			reportReq.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
			String sign = Signature.getSign(reportReq.toMap());
			reportReq.setSign(sign);

			WxReportRes reportRes = payApi.report(reportReq);

			log.info("reportRes = {}", reportRes);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "sssss";
	}


	@RequestMapping(value = "/testbatchquerycomment")
	public String testbatchquerycomment() {

		try {
			WxBatchQueryCommentReq batchQueryCommentReq = new WxBatchQueryCommentReq();

			batchQueryCommentReq.setKey(key);

			batchQueryCommentReq.setAppid(appid);
			batchQueryCommentReq.setMch_id(mchid);
			batchQueryCommentReq.setSign_type("HMAC-SHA256");
			batchQueryCommentReq.setBegin_time("20190330000000");
			batchQueryCommentReq.setEnd_time("20190601000000");
			batchQueryCommentReq.setOffset(200);
			batchQueryCommentReq.setLimit(100);

			batchQueryCommentReq.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
			String sign = Signature.getSign(batchQueryCommentReq.toMap());
			batchQueryCommentReq.setSign(sign);

			WxBatchQueryCommentRes batchQueryCommentRes = payApi.batchquerycomment(batchQueryCommentReq, new File(certFilePath), certPassword);

			log.info("batchQueryCommentRes = {}", batchQueryCommentRes);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "sssss";
	}

	@RequestMapping(value = "/testtransfers")
	public String testtransfers() {

		try {
			WxTransfersReq transfersReq = new WxTransfersReq();

			transfersReq.setKey(key);

			transfersReq.setMch_appid(appid);
			transfersReq.setMchid(mchid);
			transfersReq.setPartner_trade_no("test");
			transfersReq.setOpenid("testOpenId");
			transfersReq.setCheck_name("NO_CHECK");
			transfersReq.setRe_user_name("");
			transfersReq.setAmount(100);
			transfersReq.setDesc("test提现");
			transfersReq.setSpbill_create_ip("127.0.0.1");

			transfersReq.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
			String sign = Signature.getSign(transfersReq.toMap());
			transfersReq.setSign(sign);

			WxTransfersRes transfersRes = payApi.transfers(transfersReq, new File(certFilePath), certPassword);

			log.info("transfersRes = {}", transfersRes);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "sssss";
	}

	@RequestMapping(value = "/testgettransferinfo")
	public String testgettransferinfo() {

		try {
			WxGetTransferInfoReq transferInfoReq = new WxGetTransferInfoReq();

			transferInfoReq.setKey(key);

			transferInfoReq.setAppid(appid);
			transferInfoReq.setMch_id(mchid);
			transferInfoReq.setPartner_trade_no("test");

			transferInfoReq.setNonce_str(RandomStringGenerator.getRandomStringByLength(32));
			String sign = Signature.getSign(transferInfoReq.toMap());
			transferInfoReq.setSign(sign);

			WxGetTransferInfoRes transferInfoRes = payApi.gettransferinfo(transferInfoReq, new File(certFilePath), certPassword);

			log.info("transferInfoRes = {}", transferInfoRes);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "sssss";
	}

}


